const DB = require('../../../utils/db')
// 引入jwt token工具
const JwtUtil = require('../../../utils/jwt')
/**
 * GET, 参数groupid
 * 申请进入群聊
 */

module.exports = async (ctx) => {
  // 获取token
  let token = ctx.request.header.authorization
  let jwt = new JwtUtil(token)
  // 用token获取到userid
  let userid = jwt.verifyToken()
  // 查询是否是群成员
  const isMember = await DB.query(
    `select * from user_group where (userid='${userid}' and groupid='${ctx.request.query.groupid}')`
  )
  if (isMember.length === 1) {
    ctx.body = {
      code: 0,
      data: '已经是群成员啦',
    }
  } else {
    // 查询申请信息
    const applyres = await DB.query(
      `select applyStatus from user_group_apply where userid='${userid}' and groupid='${ctx.request.query.groupid}'`
    )
    console.log(applyres)
    // 如果已经申请过
    if (applyres.length > 0 && applyres[0].applyStatus === 0) {
      ctx.body = {
        code: 0,
        data: applyres,
      }
    } else {
      // 没有申请过,插入申请信息
      const res = await DB.query(
        `insert user_group_apply(userid,groupid,applyStatus) values('${userid}','${ctx.request.query.groupid}',0)`
      )
      // 查询申请信息
      const applyres = await DB.query(
        `select applyStatus from user_group_apply where userid='${userid}' and groupid='${ctx.request.query.groupid}'`
      )
      ctx.body = {
        code: 0,
        data: applyres,
      }
    }
  }
}
